<template>
  <div class="app-container" id="AllPage">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:result_personal:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-printer"
          size="mini"
          v-hasPermi="['system:result_personal:export']"
          v-print="print"
        >打印</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-back"
          size="mini"
          @click="outerTest"
        >返回</el-button>
      </el-col>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>
    <el-row>
      <el-col>
        <div class="letter-opening">《{{combinationName}}》团体报告</div>
      </el-col>
      <el-col>
        <el-descriptions class="center" title="一、基本信息" :column="2" border>
          <el-descriptions-item>
            <template slot="label">
              测试量表
            </template>
            {{result_personalList[0].scaleTitleShow}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              生成时间
            </template>
            {{result_personalList[0].createTime}}
          </el-descriptions-item>
        </el-descriptions>
      </el-col>
      <el-col>
        <el-descriptions class="center" title="二、测验简介"  direction="vertical">
          <el-descriptions-item v-if="result_personalList">
            {{result_personalList[0].scale.scaleDetails}}
          </el-descriptions-item>
        </el-descriptions>
      </el-col>
      <el-col>
        <div class="center">
            <div style="font-weight: bold;">三、团体平均状态</div>
        </div>
        <table class="header-table">
          <tr>
            <td>项目</td>
            <td>平均值</td>
            <td>标准差</td>
            <td>最大值</td>
            <td>最小值</td>
          </tr>
          <tr v-for= "(data, index) in this.factortotal" :key="index">
            <td>{{ factorNameList[index] }}</td>
            <td>{{ averageList[index] }}</td>
            <td>{{ squareList[index] }}</td>
            <td>{{ bigList[index] }}</td>
            <td>{{ smallList[index] }}</td>
          </tr>
        </table>
      </el-col>
      <el-col>
        <div class="center">
            <div style="font-weight: bold;">四、人员分布</div>
        </div>
        <table class="header-table">
          <tr>
            <td>维度</td>
            <td>状态名称</td>
            <td>分布</td>
            <td>预警类别</td>
          </tr>
          <tr v-for="(data, index) in parsedScore" :key="index">
            <td>{{ data.factorName }}</td>
            <td>{{ data.score }}</td>
            <td>{{ data.description }}</td>
            <td>{{ data.heart }}</td>
          </tr>
        </table>
      </el-col>
    </el-row>
    
  </div>
</template>

<script>
import { listResult_total, getResult_personal, delResult_personal, addResult_personal, updateResult_personal } from "@/api/mentalTest/personScore.js";
import { getInfo } from "@/api/login"
import Print from 'vue-print-nb';
import Vue from "vue";
Vue.use(Print);
export default {
  name: "report",
  data() {
    let that = this
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 个人测评成绩报告表格数据
      result_personalList: {},
      //对应的量表信息
      scaleList:null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      combinationId:null,
      combinationName:null,
      resultId:null,
      //解析factorScore为对象
      parsedScore : [],
      //解析factorResult为对象
      parsedResult: {},
      userAnswerList:[],
      //判断登录者的身份
      roleName:null,
      //求每个因子对应的总数
      sumList:[],
      //求每个因子对应的平均值
      averageList:[],
      //求每个因子的最大值
      bigList:[],
      //求每个因子的最小值
      smallList:[],
      //因子名字
      factorNameList:[],
      //维度个数
      factortotal:0,
      //求每个因子的标准差
      squareList:[],

      // 查询参数
      queryParams: {
        scaleId: null,
        scaleTitleShow: null,
        userId: null,
        loginName: null,
        userName: null,
        countScore: null,
        factorScore: null,
        resultContent: null,
        factorResult: null,
        userAnswer: null,
        classesName: null,
        deptName: null,
        createTime:null,
        combinationId:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      print: {
        id: 'AllPage',
        // popTitle: '配置页眉标题', // 打印配置页上方的标题
        // extraHead: '打印', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
        // preview: true, // 是否启动预览模式，默认是false
        // previewTitle: '预览的标题', // 打印预览的标题
        // previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
        zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
        previewBeforeOpenCallback () { console.log('正在加载预览窗口！'); console.log(that.msg, this) }, // 预览窗口打开之前的callback
        previewOpenCallback () { console.log('已经加载完预览窗口，预览打开了！') }, // 预览窗口打开时的callback
        beforeOpenCallback () { console.log('开始打印之前！') }, // 开始打印之前的callback
        openCallback () { console.log('执行打印了！') }, // 调用打印时的callback
        closeCallback () { console.log('关闭了打印工具！') }, // 关闭打印的callback(无法区分确认or取消)
        clickMounted () { console.log('点击v-print绑定的按钮了！') },
        // url: 'http://localhost:8080/', // 打印指定的URL，确保同源策略相同
        // asyncUrl (reslove) {
        //   setTimeout(() => {
        //     reslove('http://localhost:8080/')
        //   }, 2000)
        // },
        standard: '',
        extarCss: ''
      }
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.getRole();
  },
  computed: {
    
  },
  methods: {
    //获取路由参数
    getRouterQuery () {
        this.combinationId = this.$router.history.current.query.combinationId
        this.combinationName = this.$router.history.current.query.combinationName
    },
    /** 查询对应的测评成绩报告列表 */
    getList() {
      this.loading = true;
      this.getRouterQuery();
      // console.log("Id",this.combinationId);
      this.queryParams.combinationId = this.combinationId;
      listResult_total(this.queryParams).then(response => {
        // console.log("response.rows",response.rows);
        // this.result_personalList = response.rows;
        this.result_personalList = JSON.parse(JSON.stringify(response.rows));
        this.total = response.total;
        console.log("result_personalList",this.result_personalList);
        // console.log("total",this.total);
        // 解析 factorScore 为对象
        // console.log("factorScore",this.result_personalList[0].factorScore);
        let k = 0;
        for(let k = 0 ; k < this.total ; k++){
          this.sumList[k] = 0;
          this.averageList[k] = 0;
          this.squareList[k] = 0;
          this.bigList[k] = 0;
          this.smallList[k] = 10000;
        }

        //看维度个数是多少个
        let scorePairs = this.result_personalList[k].factorScore.split("\r\n");
        for (let pair of scorePairs) {
          this.factortotal++;
        }
        this.factortotal -=1;
        console.log("factortotal",this.factortotal);

        //存数组
        let twoData = new Array(this.factortotal); // 外层为维度个数
        for (let i = 0; i < twoData.length; i++) {
          twoData[i] = new Array(this.total).fill(0); // 每个槽位都是一个包含团体个数的数组
        }

        k = 0;
        while(k < this.total){
          console.log("k的大小",k);
          console.log("每一行的数据",this.result_personalList[k]);
          let scorePairs = this.result_personalList[k].factorScore.split("\r\n");
          // console.log("scorePairs",scorePairs);
          // let i = 0;
          let factoradd = 0;
          for (let pair of scorePairs) {
            let trimmedPair = pair.trim(); // 去除两侧的空格
            console.log("trimmedPair",trimmedPair);
            if (trimmedPair) {
              let [factor, value] = trimmedPair.split(" = "); // 使用 " = " 分隔因子和值
              this.factorNameList[factoradd] = factor.trim(); // 去除因子名称两侧的空格
              let score = parseFloat(value.trim()); // 解析值为浮点数
              twoData[factoradd][k] = score;
              // this.sumList[factoradd] += score;
              //求最小值
              if(score < this.smallList[factoradd]){
                this.smallList[factoradd] = score;
              }
              //求最大值
              if(score > this.bigList[factoradd]){
                this.bigList[factoradd] = score;
              }
            }
            factoradd++;
          }
          //求平均值
          // for(factoradd = 0 ; factoradd < this.factortotal ; factoradd++){
          //   this.averageList[factoradd] = this.sumList[factoradd]/this.total;
          // }
          k++;
        }
        for(let i = 0; i < this.factortotal ; i++){
          // 计算平均值
          this.averageList[i] = twoData[i].reduce((sum, value) => sum + value, 0) / twoData[i].length;

          // 计算每个数据点与平均值的差的平方
          const squaredDifferences = twoData[i].map(value => Math.pow(value - this.averageList[i], 2));

          // 计算方差
          const variance = squaredDifferences.reduce((sum, value) => sum + value, 0) / twoData[i].length;

          // 计算标准差
          this.squareList[i] = Math.sqrt(variance);

        }
        //查看数据
        for(let factoradd = 0 ; factoradd < this.factortotal ; factoradd++){
          console.log("每个因子的数据",twoData[factoradd]);
          console.log("因子名称",this.factorNameList[factoradd]);
          console.log("平均值",this.averageList[factoradd]);
          console.log("最大值",this.bigList[factoradd]);
          console.log("最小值",this.smallList[factoradd]);
          console.log("标准差",this.squareList[factoradd]);
        }
      }); 
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        resultId: null,//测评结果id
        scaleId: null,//测评量表id
        scaleTitleShow: null,//测评量表名称
        userId: null,//用户id
        loginName: null,//登录账号
        userName: null,//用户昵称
        countScore: null,//总分
        factorScore: null,//因子的分数
        resultContent: null,//分数范围和结果提示
        factorResult: null,//因子的分数范围及结果提示
        userAnswer: null,//用户选择数据
        createTime: null,//创建时间
        updateTime: null,//更新修改时间
        classesName: null,//班级
        deptName: null//学院
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.resultId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    //获取登录者的身份
    getRole(){
      getInfo().then(response =>{
        console.log("身份",response.user.roles[0].roleName);
        this.roleName = response.user.roles[0].roleName;
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      console.log("result_personalList",this.result_personalList);
      updateResult_personal(this.result_personalList).then(response => {
        this.$modal.msgSuccess("添加评语成功");
        this.open = false;
        this.getList();
      });
    },
    //因子分数对应分数范围得到结果提示
    getResult(score) {
      // 解析 factorResult 为对象
      console.log("factorResult",this.result_personalList.factorResult);
      const resultPairs = this.result_personalList.factorResult.split(";");
      console.log("resultPairs",resultPairs);
      for (const pair of resultPairs) {
        const trimmedpair = pair.trim();
        // const trimmedpair1 = trimmedpair.replace(/\n/g, "");
        // console.log("trimmedpair1",trimmedpair1);
        if (trimmedpair) {
          const trimmedpair1 = trimmedpair.split("\n");
          console.log("trimmedpair1",trimmedpair1);
          // const [range, description] = trimmedpair1.split(":");
          // const [min, max] = range.split("-");
          // this.parsedResult[min.trim()] = description.trim();
          // this.parsedResult[max.trim()] = description.trim();
          // console.log("parsedResult",this.parsedResult);
        }
      }
      // console.log("解析好的factorResult对象",this.parsedResult);
      // 根据分数获取对应的内容
      // for (const range in this.parsedResult) {
      //   if (score >= parseFloat(range)) {
      //     return this.parsedResult[range];
      //   }
      // }
      return "未知内容";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const resultId = row.resultId || this.ids
      getResult_personal(resultId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改个人测评成绩报告";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.resultId != null) {
            updateResult_personal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addResult_personal(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const resultIds = row.resultId || this.ids;
      this.$modal.confirm('是否确认删除个人测评成绩报告编号为"' + resultIds + '"的数据项？').then(function() {
        return delResult_personal(resultIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$modal.confirm('确认导出该危机预警信息吗？').then(response => {
        this.download('system/result_personal/export', {
          ...this.queryParams
        }, `result_personal_${new Date().getTime()}.xlsx`)
      })
    },/** 打印按钮操作 */
    handleExport1() {
      this.$modal.confirm('确认打印该危机预警信息吗？').then(response => {
        this.download('system/result_personal/export', {
          ...this.queryParams
        }, `result_personal_${new Date().getTime()}.pdf`)
      })
    },
    // 返回路由跳转
    outerTest () {
      this.$router.push({
        path: '/mentalTest/totalInfo',
        query: {
        }
      })
    }
  }
}
</script>
<style>
.letter-opening {
  display: flex;
  justify-content: center;
  align-content: center;
  font-size: 30px;
  font-weight: bold;
}
.header-table {
    margin: 0 auto;
    border: 1px solid #e6ebf5;
    border-collapse: collapse;
    margin-top: 20px;
    width: 900px;
    height: 100px;
}
.header-table td{
    border: 1px solid #e6ebf5;
    text-align: center;
}
.tail-table{
    margin: 0 auto;
    border: 1px solid #e6ebf5;
    border-collapse: collapse;
    margin-top: 20px;
    width: 900px;
    height: 100px;
}
.tail-table td{
    border: 1px solid #e6ebf5;
    text-align: center;
}
.center {
    width: 900px;
    margin: 20px auto;
}
@page {
  margin: 0;
}
</style>

